package com.gqzmy.springboot3.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author 周小哥  gqzmy@163.com 2022/12/1 20:20
 */

public class TraceIdInterceptor implements HandlerInterceptor {

    public static final Logger logger = LoggerFactory.getLogger(TraceIdInterceptor.class);

    public static final String APP_ID = "appId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("preHandle...");
        MDC.put(APP_ID, "SpringBoot3");
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("afterCompletion...");
        MDC.remove(APP_ID);
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
